package cn.com.egova.mahjong;

import android.app.Application;
import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class MyApplication extends Application {
    private static final String DB_NAME = "database.db";
    private static final String DB_PATH = Environment.getExternalStorageDirectory() + "/mahjong";

    @Override
    public void onCreate() {
        super.onCreate();
        setDatabase();
    }

    /**
     * 设置greenDao
     */
    private void setDatabase() {
        File dir = new File(DB_PATH);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                return;
            }
        }
        copyAssetsToSD(DB_PATH + File.separator + DB_NAME, DB_NAME);
    }

    private void copyAssetsToSD(String outPath, String fileName) {
        try {
            File outFile = new File(outPath);
            if (outFile.exists()) {
                return;
            }
            InputStream inputStream = getAssets().open(fileName);
            FileOutputStream fileOutputStream = new FileOutputStream(outFile);
            byte[] buffer = new byte[1024];
            int byteRead;
            while (-1 != (byteRead = inputStream.read(buffer))) {
                fileOutputStream.write(buffer, 0, byteRead);
            }
            inputStream.close();
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
